package com.yutel.phone.binh.data.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class HttpMapper {
	private final static String TAG = "HttpMapper";
	DataMap data;

	public HttpMapper(DataMap data) {
		this.data = data;
	}

	public Object query(String url) {
		Object obj = null;
		URL curl = null;
		InputStream input = null;
		HttpURLConnection conn = null;
		try {
			if (url.indexOf("http") >= 0) {
				curl = new URL(url);
			} else {
				curl = new URL("http://" + url);
			}
			conn = (HttpURLConnection) curl.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(20000);
			if (conn.getResponseCode() == 200) {
				input = conn.getInputStream();
				obj = data.data(input);
			}
			return obj;
		} catch (Exception e) {
			Log.e(TAG, "query", e);
			return null;
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					Log.e(TAG, "input.close", e);
				}
			}
		}
	}

	public interface DataMap {
		public Object data(InputStream input);
	}
}
